<template>
  <view class="recruit-container">
    <!-- 页面标签 -->
    <recruit-tabs v-model="activeTab" />
    
    <!-- 岗位列表 -->
    <view v-if="activeTab === 'list'" class="recruit-content">
      <!-- 搜索框 -->
      <recruit-search-bar
        v-model="searchKeyword"
        @search="handleSearch"
        @clear="clearSearch"
      />
      
      <!-- 筛选组件 -->
      <recruit-filter 
        :types="recruitTypes" 
        :default-type="filterOptions.type"
        :default-sort="filterOptions.sort"
        @filter-change="handleFilterChange"
      />
      
      <!-- 列表内容 -->
      <view class="recruit-list">
        <template v-if="filteredList.length > 0">
          <recruit-item 
            v-for="item in filteredList" 
            :key="item.id"
            :item="item"
            :favorites="userFavorites"
            @detail="goToDetail"
            @apply="goToApply"
            @favorite="toggleFavorite"
          />
        </template>
        <empty-recruit 
          v-else 
          text="暂无符合条件的招聘信息" 
          show-button
          button-text="重置筛选"
          @action="resetFilter"
        />
      </view>
      
      <!-- 加载更多 -->
      <recruit-load-more
        v-if="filteredList.length > 0"
        :loading="loading"
        :has-more="hasMore"
        @load-more="loadMore"
      />
    </view>
    
    <!-- 我的申请 -->
    <view v-else-if="activeTab === 'my'" class="recruit-content">
      <view class="recruit-my">
        <template v-if="userApplications.length > 0">
          <view class="recruit-my__list">
            <view 
              v-for="item in userApplications" 
              :key="item.id"
              class="recruit-my__item"
              @click="goToApplicationDetail(item.id)"
            >
              <recruit-application-item
                :title="getRecruitTitle(item.recruitId)"
                :status="item.status"
                :create-time="item.createTime"
                :feedback="item.feedback"
              />
            </view>
          </view>
        </template>
        <empty-recruit 
          v-else 
          text="您还没有申请记录" 
          show-button
          button-text="去看看招聘"
          @action="switchTab('list')"
        />
      </view>
    </view>
    
    <!-- 我的收藏 -->
    <view v-else-if="activeTab === 'favorite'" class="recruit-content">
      <view class="recruit-favorite">
        <template v-if="userFavorites.length > 0">
          <view class="recruit-favorite__list">
            <recruit-item 
              v-for="item in favoriteRecruits" 
              :key="item.id"
              :item="item.recruitInfo"
              :favorites="userFavorites"
              @detail="goToDetail"
              @apply="goToApply"
              @favorite="toggleFavorite"
            />
          </view>
        </template>
        <empty-recruit 
          v-else 
          text="您还没有收藏的岗位" 
          show-button
          button-text="去看看招聘"
          @action="switchTab('list')"
        />
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useStore } from 'vuex';
import { recruitTypes } from '@/mock/recruit';

// 导入组件
import RecruitFilter from '@/components/recruit/RecruitFilter.vue';
import RecruitItem from '@/components/recruit/RecruitItem.vue';
import EmptyRecruit from '@/components/recruit/EmptyRecruit.vue';
import RecruitTabs from '@/components/recruit/RecruitTabs.vue';
import RecruitSearchBar from '@/components/recruit/RecruitSearchBar.vue';
import RecruitLoadMore from '@/components/recruit/RecruitLoadMore.vue';
import RecruitApplicationItem from '@/components/recruit/RecruitApplicationItem.vue';
import RecruitFavoriteItem from '@/components/recruit/RecruitFavoriteItem.vue';

// 初始化store
const store = useStore();

// 页面状态
const activeTab = ref('list'); // list-岗位列表, my-我的申请, favorite-我的收藏

// 搜索关键词
const searchKeyword = ref('');

// 筛选选项
const filterOptions = reactive({
  type: 0, // 0表示全部
  sort: 'latest' // 默认按最新排序
});

// 计算属性：招聘列表
const recruitList = computed(() => store.getters['recruit/getRecruitList']);

// 计算属性：加载状态
const loading = computed(() => store.getters['recruit/loading']);

// 计算属性：是否有更多数据
const hasMore = computed(() => store.getters['recruit/hasMore']);

// 计算属性：用户申请记录
const userApplications = computed(() => store.getters['recruit/getUserApplications']);

// 计算属性：用户收藏
const userFavorites = computed(() => store.getters['recruit/getUserFavorites']);

// 计算属性：根据筛选条件过滤后的列表
const filteredList = computed(() => {
  let result = [...recruitList.value];
  
  // 按类型筛选
  if (filterOptions.type !== 0) {
    result = result.filter(item => item.type === filterOptions.type);
  }
  
  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    result = result.filter(item => 
      item.title.toLowerCase().includes(keyword) || 
      item.organization.toLowerCase().includes(keyword) || 
      item.description.toLowerCase().includes(keyword)
    );
  }
  
  // 排序
  if (filterOptions.sort === 'latest') {
    result.sort((a, b) => b.createTime - a.createTime);
  } else if (filterOptions.sort === 'hot') {
    result.sort((a, b) => {
      if (a.isHot && !b.isHot) return -1;
      if (!a.isHot && b.isHot) return 1;
      return b.applied / b.positions - a.applied / a.positions;
    });
  } else if (filterOptions.sort === 'deadline') {
    result.sort((a, b) => a.deadline - b.deadline);
  }
  
  return result;
});

// 计算属性：收藏的招聘信息
const favoriteRecruits = computed(() => {
  return userFavorites.value;
});

// 页面加载时获取数据
onMounted(() => {
  // 重置筛选条件
  resetFilter();
  
  // 获取数据
  store.dispatch('recruit/fetchRecruitList');
  store.dispatch('recruit/fetchUserApplications');
  store.dispatch('recruit/fetchUserFavorites');
});

// 获取招聘列表
const fetchRecruitList = async () => {
  try {
    const params = {
      refresh: true,
      type: filterOptions.type === 0 ? undefined : filterOptions.type,
      keyword: searchKeyword.value || undefined,
      sort: filterOptions.sort
    };
    
    const result = await store.dispatch('recruit/fetchRecruitList', params);
    if (!result.success) {
      uni.showToast({
        title: result.message || '获取招聘列表失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取招聘列表失败', error);
    uni.showToast({
      title: '获取招聘列表失败',
      icon: 'none'
    });
  }
};

// 获取用户申请记录
const fetchUserApplications = async () => {
  try {
    const result = await store.dispatch('recruit/fetchUserApplications');
    if (!result.success) {
      console.error('获取用户申请记录失败', result.message);
    }
  } catch (error) {
    console.error('获取用户申请记录失败', error);
  }
};

// 获取用户收藏
const fetchUserFavorites = async () => {
  try {
    const result = await store.dispatch('recruit/fetchUserFavorites');
    if (!result.success) {
      console.error('获取用户收藏失败', result.message);
    }
  } catch (error) {
    console.error('获取用户收藏失败', error);
  }
};

// 切换标签页
const switchTab = (tab) => {
  activeTab.value = tab;
  searchKeyword.value = '';
};

// 处理筛选变化
const handleFilterChange = (options) => {
  filterOptions.type = options.type;
  filterOptions.sort = options.sort;
  fetchRecruitList();
};

// 处理搜索
const handleSearch = () => {
  fetchRecruitList();
};

// 清除搜索
const clearSearch = () => {
  searchKeyword.value = '';
  fetchRecruitList();
};

// 重置筛选
const resetFilter = () => {
  searchKeyword.value = '';
  filterOptions.type = 0;
  filterOptions.sort = 'latest';
  fetchRecruitList();
};

// 加载更多
const loadMore = () => {
  if (loading.value || !hasMore.value) return;
  store.dispatch('recruit/fetchRecruitList', { refresh: false });
};

// 跳转到详情页
const goToDetail = (id) => {
  uni.navigateTo({
    url: `/pages/recruit/detail?id=${id}`
  });
};

// 跳转到申请页
const goToApply = (id) => {
  uni.navigateTo({
    url: `/pages/recruit/apply?id=${id}`
  });
};

// 跳转到申请详情页
const goToApplicationDetail = (id) => {
  uni.navigateTo({
    url: `/pages/recruit/application?id=${id}`
  });
};

// 收藏/取消收藏
const toggleFavorite = async (id) => {
  try {
    // 检查是否已收藏
    const isFavorite = userFavorites.value.some(item => item.recruitId === id);
    
    // 调用Vuex action
    const result = await store.dispatch('recruit/toggleFavorite', { id, isFavorite });
    
    if (result.success) {
      uni.showToast({
        title: result.message,
        icon: 'success'
      });
    } else {
      uni.showToast({
        title: result.message || '操作失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('收藏操作失败', error);
    uni.showToast({
      title: '操作失败，请重试',
      icon: 'none'
    });
  }
};

// 获取招聘标题
const getRecruitTitle = (recruitId) => {
  const recruit = recruitList.value.find(item => item.id === recruitId);
  return recruit ? recruit.title : '未知岗位';
};

// 获取申请状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待审核',
    'viewed': '已查看',
    'interview': '待面试',
    'accepted': '已录用',
    'rejected': '已拒绝'
  };
  return statusMap[status] || '未知状态';
};

// 格式化日期
const formatDate = (timestamp) => {
  const date = new Date(timestamp);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};
</script>

<style lang="scss" scoped>
.recruit-container {
  min-height: 100vh;
  background-color: #f6f7fb;
  padding-bottom: 20px;
}

.recruit-container {
  min-height: 100vh;
  background-color: #f6f7fb;
  padding-bottom: 20px;
}

.recruit-content {
  padding: 8px 16px;
}

.recruit-list {
  padding: 12px 0;
  margin-top: 8px;
}

.recruit-my,
.recruit-favorite {
  padding: 16px 0;
  
  &__list {
    margin-bottom: 16px;
  }
  
  &__item {
    background-color: #ffffff;
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 16px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
    transition: transform 0.2s, box-shadow 0.2s;
    
    &:active {
      transform: scale(0.98);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    }
    
    &-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
    }
    
    &-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }
    
    &-status {
      font-size: 12px;
      padding: 3px 10px;
      border-radius: 12px;
      font-weight: 500;
      
      &--pending {
        background-color: #e6f7ff;
        color: #1890ff;
      }
      
      &--viewed {
        background-color: #f6ffed;
        color: #52c41a;
      }
      
      &--interview {
        background-color: #fff7e6;
        color: #fa8c16;
      }
      
      &--accepted {
        background-color: #f6ffed;
        color: #52c41a;
      }
      
      &--rejected {
        background-color: #fff1f0;
        color: #f5222d;
      }
    }
    
    &-time {
      font-size: 13px;
      color: #999;
      margin-bottom: 10px;
    }
    
    &-feedback {
      font-size: 13px;
      color: #666;
      background-color: #f9f9f9;
      padding: 10px;
      border-radius: 8px;
      line-height: 1.5;
    }
  }
}
</style>